from ss.file import File
from ss.record import Record, SSNAME

__author__ = 'andrey'

FILENAME_ENCODING = 'cp1251'

class ProjectEntry(Record):
    def _get_struct_type(self):
        return super(ProjectEntry, self)._get_struct_type() + 'hh' + SSNAME + 'h10s'
    def type(self):
        return self._data[3]
    def flags(self):
        return self._data[4]
    @property
    def name(self):
        if not hasattr(self, '_name'):
            #if self._data[7] == 0:
            #    return self._data[6][:self._data[6].find('\0')]
            #raise NotImplementedError('extract name from names.dat')
            self._name = self._data[6][:self._data[6].find('\0')].decode(FILENAME_ENCODING).encode('utf8')
        return self._name
    @property
    def phys(self):
        return self._data[9][:8]
    @property
    def isfile(self):
        return self.type() == 2
    @property
    def isproject(self):
        return self.type() == 1
    @property
    def deleted(self):
        return self.flags() & 1 == 1

    def __str__(self):
        l = ['-'] * 5
        l[0] = 'p' if self.type() == 1 else 'f'
        if self.deleted:
            l[1] = 'd'
        if self.flags() & 2 == 2:
            l[2] = 'b'
        if self.flags() & 4 == 4:
            l[3] = 'l'
        if self.flags() & 8 == 8:
            l[4] = 's'
        return ''.join(l) + ' ' + self.phys + ' ' + self.name


class ProjectFile(File):
    def __init__(self, filename):
        super(ProjectFile, self).__init__(filename)
        self._read()
        self._entries = []
        offset = 0
        while offset < len(self._data):
            entry = ProjectEntry(self._data, offset)
            self._entries.append(entry)
            offset += entry.size()

    def __iter__(self):
        return self._entries.__iter__()

    def entries(self):
        return self._entries

